// 和用户相关的状态管理
import {createSlice} from '@reduxjs/toolkit'
import {getTokey, removeToken, setToken as _setToken} from "@/utils/token";
import {getUserInfoAPI, loginAPI} from "@/apis/UserAPI";

const userStore = createSlice({
    name: 'user',
    // 数据状态
    initialState: {
        token: getTokey() || '',
        userInfo: {}
    },
    // 同步修改方法
    reducers: {
        setToken(state, action) {
            state.token = action.payload
            _setToken(action.payload)
        },
        setUserInfo(state, action) {
            state.userInfo = action.payload
        },
        // 清除token
        removeUserInfo(state) {
            state.userInfo = {}
            state.token = ''
            removeToken()
        }
    }
})

// 解构出actionCreater
const {setToken, setUserInfo, removeUserInfo} = userStore.actions

// Token异步方法封装
const fetchLogin = (loginForm) => {
    return async (dispatch) => {
        try {
            // 调用接口获取token
            // const res = await request.post('/authorizations', loginForm)
            const res = await loginAPI(loginForm)
            dispatch(setToken(res.data.token))
        } catch (error) {
            console.log(error)
        }

    }
}


// 获取用户个人信息异步方法封装
const fetchUserInfo = (loginForm) => {
    return async (dispatch) => {
        try {
            // 调用接口获取用户信息
            // const res = await request.get('/user/profile')
            const res = await getUserInfoAPI()
            dispatch(setUserInfo(res.data))
        } catch (error) {
            // 如果获取失败 清除用户信息
            dispatch(removeUserInfo())
        }

    }
}

// 获取reducer函数
const userReducer = userStore.reducer
export {setToken, fetchLogin, fetchUserInfo, removeUserInfo}
export default userReducer